package main

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"io"
	"log"
	"net"
)

func main() {
	localPort := "LOCAL_PORT"          // 本地端口号
	remoteAddr := "REMOTE_ADDRESS"    // 远程服务器地址
	remotePort := "REMOTE_SSH_PORT"   // 远程服务器的 SSH 端口号
	remoteUser := "REMOTE_USERNAME"   // 远程服务器的用户名
	remotePassword := "REMOTE_PASSWORD" // 远程服务器的密码
	remote_target_port := "3306"


	config := &ssh.ClientConfig{
		User: remoteUser,
		Auth: []ssh.AuthMethod{
			ssh.Password(remotePassword),
		},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(), // 不进行主机密钥验证
	}

	conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", remoteAddr, remotePort), config)
	if err != nil {
		log.Fatalf("Unable to connect to remote server: %s", err)
	}
	defer conn.Close()

	localListener, err := net.Listen("tcp", fmt.Sprintf(":%s", localPort))
	if err != nil {
		log.Fatalf("Unable to open local port: %s", err)
	}
	defer localListener.Close()

	log.Printf("等待连接到本地端口 %s...\n", localPort)

	for {
		localConn, err := localListener.Accept()
		if err != nil {
			log.Fatalf("Unable to accept local connection: %s", err)
		}

		remoteConn, err := conn.Dial("tcp", fmt.Sprintf("%s:%s", remoteAddr, remote_target_port))
		if err != nil {
			log.Fatalf("Unable to connect to remote server: %s", err)
		}

		go func() {
			defer remoteConn.Close()
			defer localConn.Close()

			go func() {
				_, err := io.Copy(remoteConn, localConn)
				if err != nil {
					log.Fatalf("Error copying from local to remote: %s", err)
				}
			}()

			_, err = io.Copy(localConn, remoteConn)
			if err != nil {
				log.Fatalf("Error copying from remote to local: %s", err)
			}
		}()
	}
}
